package unify.fileio;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Logger;

import unify.ShowLibrary;
import unify.data.Episode;
import unify.data.Season;
import unify.data.Show;



public class FileIO {
	private File showFile;
	private File availableFile;
	private ShowLibrary showLib;
	private final static Logger LOGGER = Logger.getLogger(FileIO.class.getName());

	public FileIO(String showFile, String availableFile) {
		super();
		this.showFile = new File(showFile);
		this.availableFile = new File(availableFile);
		this.showLib = ShowLibrary.getInstance();
	}

	public void loadShows() {
		Scanner showscanner = null;
		try {
			showscanner = new Scanner(this.showFile);
			LOGGER.finest("Initializing shows file input...");
		} catch (FileNotFoundException e) {
			LOGGER.severe("File " + this.showFile.getName() + " does not exist.");
			System.exit(1);
		}
		Show s1;
		while (showscanner.hasNext()) {
			String show = showscanner.nextLine();
			s1 = new Show(show.split(" :: ")[0]);
			try {
				s1.setCurSeason(Integer.parseInt(show.split(" :: ")[1]));
				s1.setLastEpisode(Integer.parseInt(show.split(" :: ")[2]));
			} catch (NumberFormatException e) {
				LOGGER.severe("Invalid number format for " + show.split(" :: ")[1]
						+ " or " + show.split(" :: ")[2]);
				System.exit(1);
			}
			showLib.addShow(s1);
		}
		showscanner.close();
		LOGGER.info(showLib.shows.size() + " shows imported to library.");
	}

	public void loadAvailable() {
		Scanner showscanner = null;
		try {
			showscanner = new Scanner(this.availableFile);
			LOGGER.finest("Initializing available file input...");
		} catch (FileNotFoundException e) {
			LOGGER.warning("File " + this.availableFile.getName() + " does not exist.");
			return;
		}
		Show show;
		int availCount = 0;
		while (showscanner.hasNext()) {
			String showLine = showscanner.nextLine();
			String myShowTitle = showLine.split(" :: ")[0];
			show = showLib.getShow(myShowTitle);
			if(show!=null) {
				availCount++;
				try {
					int seasonNum = (Integer.parseInt(showLine.split(" :: ")[1]));
					int episodeNum = (Integer.parseInt(showLine.split(" :: ")[2]));
					String link = showLine.split(" :: ")[3];
					String label = showLine.split(" :: ")[4];
					Season season = show.findSeason(seasonNum);
					if(season==null) {
						season = show.addSeason(seasonNum);
					}
					season.addEpisode(episodeNum, link, label);
				} catch (NumberFormatException e) {
					LOGGER.severe("Invalid number format for " + showLine.split(" :: ")[1]
							+ " or " + showLine.split(" :: ")[2]);
					System.exit(1);
				}
			}
			else {
				LOGGER.warning("Error, show not found, check show file.");
			}
		}
		LOGGER.info(availCount + " episodes imported to library.");
		showscanner.close();
	}

	public void updateShowFile() {
		boolean append = false;
		for (int i = 0; i < showLib.shows.size(); i++) {
			Show s1 = showLib.shows.get(i);
			try {
				String data = s1.getTitle() + " :: " + s1.getCurSeason() + " :: "
						+ s1.getLastEpisode() + "\n";
				FileWriter fileWritter = new FileWriter(this.showFile.getName(), append);
				BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
				bufferWritter.write(data);
				bufferWritter.close();
			} catch (IOException e) {
				LOGGER.severe("IO Error");
			}
			append = true;
		}
		LOGGER.fine("Show file updated.");
	}

	public void updateAvailableFile() {
		boolean append = false;
		for(int i = 0; i < showLib.shows.size(); i++) {
			Show s1 = showLib.shows.get(i);
			for(Season season : s1.seasons) {
				for(Episode myEp : season.getEpisodes()) {
					try {
						String link = myEp.getLink();
						String linkLabel = myEp.getLinkLabel();
						if(link.equals("")) {
							link = " ";
							linkLabel = " ";
						}
						String data = s1.getTitle() + " :: " + season.getNumber() + " :: "
								+ myEp.getNumber() + " :: " + link + " :: " + linkLabel + "\n";
						FileWriter fileWritter = new FileWriter(this.availableFile.getName(), append);
						BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
						bufferWritter.write(data);
						bufferWritter.close();
						append = true;
					} catch (IOException e) {
						LOGGER.severe("IO exception: " + e.toString());
						System.exit(1);
					}
				}
			}
		}
		if(!append) {
			File f = new File("available.txt");
			if (f.exists()) {
				f.delete();
			}
		}
		LOGGER.fine("Available file updated.");
	}
}
